<?php
class GroupsController extends AppController{

    public $name = 'Groups';

    public function add(){
       if(!empty($this->data)){
           //debug($this->data);
            $this->Group->create();
            if(empty($this->data['Group']['parent_id'])){
                $this->data['Group']['parent_id'] = 0;
            }
            if($this->Group->save($this->data)){
                $this->Session->setFlash(__('The Group has been saved', true));
            }else{
                $this->Session->setFlash(__('The Group could not be saved. Please, try again.', true));
            }
        }
        /* Redirect to user index page after add, no matter success or failed */
        $this->redirect(array('action'=>'index'));
    }

    public function edit($id = null){
        if(!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid Group', true));
            $this->redirect(array('action'=>'index'));
        }
        if(!empty($this->data)){
            if($this->Group->save($this->data)){
                $this->Session->setFlash(__('The Group has been saved', true));
            }else{
                $this->Session->setFlash(__('The Group could not be saved. Please, try again.', true));
            }
            $this->redirect(array('action'=>'index'));
        }
        if(empty($this->data)){
            $this->Response->ajax();
            $this->data = $this->Group->read(null, $id);
            $groups = $this->Group->find('list');
            $this->set('parents', $groups);
        }
    }

    public function security($id=null){
        /* Redirect on invalid security request */
        if(!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid Group', true));
            $this->redirect(array('action'=>'index'));
        }
        /* Save changes and redirect to Index page */
        $aro =& $this->Acl->Aro;
        $aco =& $this->Acl->Aco;
        if(!empty($this->data)){
            //debug($this->data);
            // lets get the Aro i.e. the group
            $aro_foreign_key = $this->data['Group']['id'];
            $aro_record = $aro->findByAlias('Group:'.$aro_foreign_key);
            $aro_alias = $aro_record['Aro']['alias'];
            $aco_of_aro = $aro_record['Aco'];
            // lets run through the security selection
            $sec_access = $this->data['Group']['SecurityAccess'];
            foreach($sec_access as $aco_id => $access_type){
                $aco_record = $aco->findById($aco_id);
                $model_plural = Inflector::pluralize($aco_record['Aco']['model']);
                if($access_type == 'allow'){
                    $this->Acl->allow($aro_alias, $model_plural.'/'.$aco_record[ 'Aco' ][ 'alias' ], '*');
                }elseif($access_type == 'deny'){
                    $this->Acl->deny( $aro_alias, $model_plural.'/'.$aco_record[ 'Aco' ][ 'alias' ], '*');
                }
            }
            $this->Session->setFlash(__('Security Changes has been saved', true));
            $this->redirect(array('action'=>'index'));
        }
        // list the whole tree & the details of the Aco records
        $aco_tree = $aco->generateTreeList();
        $aco_records = $aco->find('all');

        $acos = array();
        $current_alias = $this->Group->name.':'.$id;
        foreach($aco_tree as $item){
            $aco_selected = '';
            $aco_id = str_replace('_', '', $item);
            $aco_type = preg_match('/_/', $item) ? 'action' : 'controller';
            foreach($aco_records as $aco){
                if($aco['Aco']['id'] == $aco_id){
                    /* generate alias, different for controller and action ACO
                     in which, controller alias is Pluralized{ControllerName},
                    and action alias {ControllerName}.{ActionName} */
                    $aco_alias = $aco_type == 'controller'
                        ? $aco['Aco']['alias']
                        : /*$aco['Aco']['model'] .'.'. */$aco['Aco']['alias'];
                    /* check if the current item is allowed or denied */
                    $aros = $aco['Aro'];
                    foreach($aros as $aro){
                        if($aro['alias'] == $current_alias){
                            if(($aro[ 'Permission' ][ '_create' ] == 1) &&
                                ($aro[ 'Permission' ][ '_read' ] == 1) &&
                                ($aro[ 'Permission' ][ '_update' ] == 1) &&
                                ($aro[ 'Permission' ][ '_delete' ] == 1)){
                                //debug("Allowed action {$current_alias} : {$alias}");
                                $aco_selected = 'allow';
                                break;
                            }else{
                                //debug("Denied action {$current_alias} : {$alias}");
                                $aco_selected = 'deny';
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            $acos[] = array(
                'id' =>$aco_id,
                'type'=>$aco_type,
                'alias'=>$aco_alias,
                'selected'=>$aco_selected
            );
        }
        $this->set('acos', $acos);
        /* query for Group to security */
        if(empty($this->data)){
            $this->data = $this->Group->read(null, $id);
        }
    }

    public function index(){
        /* For group list*/
        $this->Group->recursive = 0;
        $this->set('groups', $this->paginate());
        /* for the group parent listing */
        $this->set('parents', $this->Group->find('list'));
    }

    public function view($id = null){
        if(!$id){
            $this->Session->setFlash(__('Invalid Group.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->set('group', $this->Group->read(null, $id));
    }

    public function check(){
        if(!empty($this->data)){
            $group = $this->Group->findByName($this->data['Group']['name']);
            if(empty($group['Group']['name'])){
                $this->Response->json(true, 'Group name check success', $group, null);
            }else{
                $this->Response->json(false, 'Group name check failure', $group['Group']['name'], null);
            }
        }else{
            $this->Response->json(false, 'Invalid Group name check request', null, null);
        }
    }

}
?>